package com.apes.autoparts.searcher.vin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.searcher.DataSource;
import com.apes.autoparts.searcher.repository.AutopartsDao;
import com.apes.framework.api.DomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;

@Component
public class EpcSubgroupSearcher<T, R> extends DomainService implements SubgroupSearcher<T, R> {

    @Autowired
    AutopartsDao autopartsDao;

    @Override
    public R parse(T element) {
        return (R) getSubgroup((JSONObject) element);
    }

    @Override
    public String[] getSource() {
        return new String[]{DataSource.EPC.name()};
    }


    /***
     * 根据上一级获取下一级
     * @param param(cata_level my_model_std_id epc_bbmc)
     * @return
     */
    private JSONObject getSubgroup(JSONObject param) {
        JSONObject returnJson = new JSONObject();
        returnJson.put("dataSource", DataSource.EPC.name());
        JSONArray subgroups = autopartsDao.getSubgroupForEpc(param);
        if (subgroups.size() != 0) {
            // 转化数据
            subgroups = subgroups.stream().map(json -> {
                JSONObject tempJson = (JSONObject) json;
                return this.invoke("autoparts.catalogConvert", tempJson);
            }).collect(Collectors.toCollection(JSONArray::new));

            returnJson.put("data", subgroups);
        } else {
            returnJson.put("data", new JSONArray());
        }
        return returnJson;
    }

}
